package com.jnzc.ocr.serv.shop.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.jnzc.ocr.common.bean.Tree;
import com.jnzc.ocr.serv.shop.entity.ShopGoods;
import com.jnzc.ocr.serv.shop.entity.ShopGoodsSku;
import com.jnzc.ocr.serv.shop.entity.ShopProductAttr;
import com.jnzc.ocr.serv.shop.filter.ShopGoodsFilter;
import com.jnzc.ocr.serv.shop.mapper.ShopGoodsMapper;
import com.jnzc.ocr.serv.shop.service.ShopGoodsService;
import com.jnzc.ocr.dependencies.serv.mybatis.MybatisServiceImpl;
import com.jnzc.ocr.serv.shop.service.ShopGoodsSkuService;
import com.jnzc.ocr.serv.shop.service.ShopProductAttrService;
import com.jnzc.ocr.serv.shop.service.ShopProductSkuService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zhangcm
 * @version 1.0, 2017-10-05
 */
@Service
public class ShopGoodsServiceImpl extends MybatisServiceImpl<ShopGoodsMapper, ShopGoods, ShopGoodsFilter> implements ShopGoodsService {

    @Autowired
    private ShopProductAttrService shopProductAttrService;

    @Autowired
    private ShopProductSkuService shopProductSkuService;

    @Autowired
    private ShopGoodsSkuService shopGoodsSkuService;

    @Override
    protected void fillEntityWrapper(EntityWrapper<ShopGoods> ew, ShopGoodsFilter filter) {
        ShopGoods entity = new ShopGoods();
        entity.setId(filter.getId());
        entity.setCategoryId(filter.getCategoryId());
        entity.setShopId(filter.getShopId());
        entity.setIfOnSale(filter.getIfOnSale());
        ew.setEntity(entity);
        if(null != filter.getWarnStockNum()) {
            ew.lt("stock_num", filter.getWarnStockNum());
        }
        if(StringUtils.isNotEmpty(filter.getKeyword())) {
            ew.andNew("no like {0} or name like {0}", "%" + filter.getKeyword() + "%");
        }
    }

    @Override
    public ShopGoods find(Long id, Long shopId) {
        ShopGoodsFilter filter = new ShopGoodsFilter();
        filter.setId(id);
        filter.setShopId(shopId);
        ShopGoods obj = super.findNotNull(filter);
        List<Tree<ShopProductAttr>> attrList = shopProductAttrService.listTree(obj.getId(), obj.getCategoryId(), obj.getShopId());
        obj.setAttrList(attrList);
        List<ShopGoodsSku> skuList = shopGoodsSkuService.listWithAttr(obj.getId(), obj.getShopId(), attrList);
        obj.setSkuList(skuList);
        return obj;
    }

    @Override
    public List<ShopGoods> listWarn(Integer warnStockNum, Long shopId) {
        ShopGoodsFilter filter = new ShopGoodsFilter();
        filter.setShopId(shopId);
        filter.setWarnStockNum(warnStockNum);
        return super.list(filter);
    }
}
